package cn.gov.customs.h2018.service.impl;

import cn.gov.customs.h2018.pojo.Article;
import cn.gov.customs.h2018.service.AsyncQuery;
import cn.gov.customs.h2018.service.ParallelQuery;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service("zjdQueryImpl")
public class ZJDQueryImpl implements ParallelQuery {

    @Autowired
    private AsyncQuery aq;

    @Override
    public List<Article> query(int articleCount) {

        List<CompletableFuture<Article>> futureList = Lists.newArrayList();
        while (articleCount>0){
            futureList.add(aq.getArticle(articleCount+""));
            articleCount--;
        }

        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();
        List<Article> resultList = Lists.newArrayList();
        futureList.forEach(e-> {
            try {
                resultList.add(e.get());
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } catch (ExecutionException ex) {
                ex.printStackTrace();
            }
        });

        return resultList;
    }
}
